package com.plusjun.gulimall.ware.listener;

import com.plusjun.common.to.OrderTO;
import com.plusjun.common.to.mq.StockLockTO;
import com.plusjun.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Resource
    WareSkuService wareSkuService;
    /**
     * 1、库存自动解锁
     * 下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就需要自动解锁
     * 2、下单失败
     * 锁库存失败
     *
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockTO to, Message message, Channel channel) throws IOException {
        System.out.println("~~~~~~~~~~收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTO to, Message message, Channel channel) throws IOException {

        System.out.println("订单关闭~~~~~~~~~~准备解锁库存的消息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
